package com.ve.clexer;

import com.ve.view.text.document.CommonLanguage;

public class ContentSeeker {
    private CharSequence content;
    private char c, lastc;
    private char nc, nlastc;// is not whitespace
    private int index, row;
    public ContentSeeker(CharSequence content) {
        this.content = content;
    }

    public ContentSeeker(char[] array) {
        this(new ArrayCharSequence(array));
    }

    public char currentChar() {
        return c;
    }

    public char lastChar() {
        return lastc;
    }

    public char currentRealChar() {//非空
        return nc;
    }

    public char lastRealChar() {
        return nlastc;
    }

    public int getIndex() {
        return index;
    }

    public int getRow() {
        return row;
    }

    public char preChar() {
        return index < content.length() - 1 ? content.charAt(index + 1) : CommonLanguage.NULL_CHAR;
    }

    public char preRealChar() {
        for (int i = index + 1; i < content.length(); i++) {
            char charAt = content.charAt(i);
            if (isReal(charAt)) {
                return charAt;
            }
        }
        return CommonLanguage.NULL_CHAR;
    }

    private boolean isReal(char charAt) {
        return charAt != CLanguage.SPACE && charAt != CLanguage.TAB;
    }

    public void begin(SeekHandler seekHandler) {
        index = 0;
        row = 1;
        lastc = c = CLanguage.NULL_CHAR;
        nlastc = nc = CLanguage.NULL_CHAR;
        for (index = 0; index < content.length(); ++index) {

            lastc = c;
            c = content.charAt(index);
            if (isReal(c)) {
                nlastc = nc;
                nc = c;
            }
            if (c == CLanguage.NEWLINE) {
                row++;
            }
            seekHandler.onSeek(c,lastc,nc,nlastc);
        }
    }

    public boolean equal(char last, char current) {
        return last==lastc&&c==current;
    }

    static class ArrayCharSequence implements CharSequence {
        private char[] data;

        public ArrayCharSequence(char[] data) {
            this.data = data;
        }

        @Override
        public int length() {
            return data.length;
        }

        @Override
        public char charAt(int index) {
            return data[index];
        }

        @Override
        public CharSequence subSequence(int start, int end) {
            char[] array = new char[end - start];
            for (int i = start; i < end; i++) {
                array[i - start] = data[i];
            }
            return String.valueOf(array);
        }
    }

    interface SeekHandler{
        void onSeek(char c,char lastc,char nc,char nlastc);
    }
}
